import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Picker, ScrollView} from '@tarojs/components'
import {AtList, AtListItem} from 'taro-ui'
import {user} from '../../utils/user.service'
import {SELLER_FOCUS, SELLER_RANKING, SELLER_PROCESS, SELLER_AMOUNT, RESOURCE_URL, CHECK_LIST_FOCUS} from '../../constants/api'
import {http} from '../../utils/http'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import Index from "../components/water-mark/index";
import './ranking.scss'

export default class Member extends Component {
  state: {
    loadMoreStatus: "more" | "loading" | "noMore"
    date: string
    tabIndex: number
    isActive: number
    tipsNum: number
    tabData: any
    tableData: any
    dateSel: string
  } = {
    loadMoreStatus: 'loading',
    tabData: [{title: '销售榜', index: 0, value: ''},{title: '核验榜', index: 3, value: '2'}, {title: '出单榜', index: 1, value: '0'}, {
      title: '拉新榜',
      index: 2,
      value: '1'
    }],
    tabIndex: 0,
    isActive: 1,
    tableData: [],
    tipsNum: 0,
    date: '',
    numsData: {},
    dateSel: '',
  }

  async componentDidShow() {
    Taro.setNavigationBarTitle({
      title: process.env.fxName + '排行榜'
    })
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    }
    const date = new Date()
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    if (process.env.TARO_ENV === 'h5') {
      month = month >= 10 ? month : '0' + month
    }
    this.setState({dateSel: year + '-' + month})
    const data = await this.getData1(year + '-' + month)
    const numsData = await this.initData(year + '-' + month)
    this.setState({tableData: data, numsData: numsData})
  }

  page = 1
  total = 0

  onPullDownRefresh() {
    Taro.stopPullDownRefresh()
  }

  async onDateChange(e) {
    const numsData = await this.initData(e.detail.value)
    this.handlerTab(0)
    this.setState({dateSel: e.detail.value, numsData: numsData})
  }

  async initData(search_time) {
    const data = await http.HGet(SELLER_AMOUNT, {search_time})
    if (data) {
      return data.data
    } else {
      return {}
    }
  }

  handlerTab(tabIndex) {
    this.page = 1
    this.setState({tabIndex, tableData: []}, async () => {
      let data = []
      if (tabIndex === 0) {
        data = await this.getData1()
      } else if (tabIndex === 1) {
        data = await this.getData2()
      } else if (tabIndex === 2) {
        data = await this.getData3()
      } else if (tabIndex === 3) {
        data = await this.getData4()
      }
      this.setState({tableData: data})
    })
  }

  timeId

  async getData1(year= '') {
    const data = await http.HGet(SELLER_FOCUS, {
      p: this.page,
      l: 10,
      pattern: this.state.isActive,
      search_time: year || this.state.dateSel
    })
    if (data && data.data) {
      this.total = data.recordsTotal
      return data.data
    } else {
      return []
    }
  }

  async getData2() {
    const data = await http.HGet(SELLER_RANKING, {
      p: this.page,
      l: 10,
      pattern: this.state.isActive,
      search_time: this.state.dateSel
    })
    if (data && data.data) {
      this.total = data.recordsTotal
      return data.data
    } else {
      return []
    }
  }

  async getData3() {
    const data = await http.HGet(SELLER_PROCESS, {
      p: this.page,
      l: 10,
      pattern: this.state.isActive,
      search_time: this.state.dateSel
    })
    if (data && data.data) {
      this.total = data.recordsTotal
      return data.data
    } else {
      return []
    }
  }

  async getData4() {
    const data = await http.HGet(CHECK_LIST_FOCUS, {
      p: this.page,
      l: 10,
      pattern: this.state.isActive,
      search_time: this.state.dateSel
    })
    if (data && data.data) {
      this.total = data.recordsTotal
      return data.data
    } else {
      return []
    }
  }

  lowerThreshold() {
    clearTimeout(this.timeId)
    this.timeId = setTimeout(async () => {
      this.setState({loadMoreStatus: 'loading'})
      let data = []
      const list = this.state.tableData
      if (this.state.tabIndex === 0) {
        if (this.page * 10 < this.total) {
          this.page++
          data = await this.getData1()
        }
      } else if (this.state.tabIndex === 1) {
        if (this.page * 10 < this.total) {
          this.page++
          data = await this.getData2()
        }
      } else if (this.state.tabIndex === 2) {
        if (this.page * 10 < this.total) {
          this.page++
          data = await this.getData3()
        }
      } else if (this.state.tabIndex === 3) {
        if (this.page * 10 < this.total) {
          this.page++
          data = await this.getData4()
        }
      }
      this.setState({loadMoreStatus: this.page * 10 < this.total ? 'more' : 'noMore', tableData: [...list, ...data]})
    }, 700)
  }

  async btnChange(isActive) {
    if (this.state.isActive === isActive) {
      return
    }
    this.page = 1
    this.setState({isActive}, async () => {
      let data = []
      if (this.state.tabIndex === 0) {
        data = await this.getData1()
      } else if (this.state.tabIndex === 1) {
        data = await this.getData2()
      } else if (this.state.tabIndex === 2) {
        data = await this.getData3()
      } else if (this.state.tabIndex === 3) {
        data = await this.getData4()
      }
      this.setState({tableData: data})
    })
  }

  showTips(num) {
    const that = this
    that.setState({tipsNum: num}, () => {
      const timer = setTimeout(() => {
        that.setState({
          tipsNum: 0
        })
        clearTimeout(timer)
      }, 2100)
    })
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const {tableData, isActive, tabData, tabIndex, date, dateSel} = this.state
    return (
      <View className='member-root'>
        <Index />
        <GzhAuth />
        <View>
          <Picker mode='date' value={date} onChange={this.onDateChange.bind(this)} fields='month'>
            <AtList>
              <AtListItem title='请选择日期' extraText={dateSel} />
            </AtList>
          </Picker>
        </View>
        <View className='foot-box'>
          <View className='tab-header'>
            {tabData && tabData.map(item =>
              <View key={item.index} className={`tab-item ${tabIndex === item.index ? 'tab-item-active' : ''}`}
                onClick={this.handlerTab.bind(this, item.index, item.value)}
              >
                <View className='line-title'>
                  {item.title}
                </View>
                <View className={`at-tabs_item_underline ${tabIndex === item.index ? 'underline-active' : ''}`} />
              </View>
            )}
          </View>
          <View className='listData'>
            {tableData.length > 0 && <ScrollView scrollY className='scroll_view' lowerThreshold={100}
              onScrollToLower={this.lowerThreshold.bind(this)}
            >
              {tableData.map((item, i) =>
                <View key={i} className='items'>
                  <View className='items-left'>
                    {i === 0 &&
                    <Image src={`${RESOURCE_URL}/resources/weapp/images/gold.png`} className='card' mode='widthFix' />}
                    {i === 1 &&
                    <Image src={`${RESOURCE_URL}/resources/weapp/images/silver.png`} className='card' mode='widthFix' />}
                    {i === 2 &&
                    <Image src={`${RESOURCE_URL}/resources/weapp/images/bronze.png`} className='card' mode='widthFix' />}
                    {(i !== 2 && i !== 1 && i !== 0) &&
                    <View className='number'>{(i + 1) >= 10 ? i + 1 : '0' + (i + 1)}</View>}
                    {item.user_nick_name || item.phone}{item.oneself && <View className='mine'>我</View>}
                  </View>
                  <View className='items-right'>
                    {(tabIndex === 0 || tabIndex === 3) && <View className='font-family-price' style={`color: ${dataColor.priceColor}`}>￥{tabIndex === 0 ? item.sum_total_fee : item.sum_ticket_total_fee}</View>}
                    {tabIndex === 1 && <View>{item.sum_order_count} 单</View>}
                    {tabIndex === 2 && <View>{item.count_seller} 人</View>}
                  </View>
                </View>
              )}
            </ScrollView>}
            {tableData.length <= 0 && <View className='no-more'>没有更多了</View>}
          </View>
          <View className='bottom-btn'>
            <View onClick={this.btnChange.bind(this, 1)}
              className={`personal-list ${isActive === 1 ? 'active' : ''}`}
            >个人榜</View>
            <View onClick={this.btnChange.bind(this, 2)}
              className={`team-list ${isActive === 2 ? 'active' : ''}`}
            >团队榜</View>
          </View>
        </View>
      </View>
    )
  }
}
